package ldk.apps.adbconnections.handlers

import ldk.apps.adbconnections.MainServer
import ldk.apps.adbconnections.beans.StringResult
import kotlin.reflect.KClass

/**
 * Created by ldkxingzhe@163.com on 2018/2/5.
 */
class ActionParser {

    private val actionMap = HashMap<Short, BaseHandler>()

    init {
        arrayListOf<KClass<out BaseHandler>>(FileListHandler::class, FileContentHandler::class).forEach {
            val value = it.java.newInstance() as BaseHandler
            if (actionMap[value.ACTION] == null){
                actionMap[value.ACTION] = value
            }else{
                throw IllegalStateException("handler's Action 重合: $value")
            }
        }
    }

    fun handle(mainServer: MainServer, action: Short, content: ByteArray?){
        val handler = actionMap[action]
        if (handler != null){
            handler.handle(mainServer, action, content)
        }else{
            val result = StringResult()
            result.errcode = 400
            mainServer.writeResponse(result)
        }
    }
}